//
//  DLSMSButton.m
//  AFNetworking
//
//  Created by dgg_hzk on 2018/11/15.
//

#import "DLSMSButton.h"

@interface DLSMSButton()

@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSTimeInterval beginTime;//进入后台时间

@end

@implementation DLSMSButton

- (void)awakeFromNib{
    [super awakeFromNib];
    [self initialize];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self initialize];
    }
    return self;
}

- (void)initialize{
    if (self.time <= 0) {
        self.time = 60;
    }
    self.activityView = [[UIActivityIndicatorView alloc] initWithFrame:self.bounds];
    self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [self addSubview:self.activityView];
    
    if (self.showButtonText.length == 0) {
        self.showButtonText = @"发送验证码";
    }
    [self setTitle:self.showButtonText forState:UIControlStateNormal];
    [self setTitle:self.showButtonText forState:UIControlStateHighlighted];
    [self addTarget:self action:@selector(smsButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    if (self.isRevise) {
        self.backgroundColor = self.showStopBackColor;
        [self setTitleColor:self.showStopTextColor forState:UIControlStateNormal];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clockWillResignAction) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clockBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)startClock{
    if(self.time <= 0){
        self.time = 60;
    }
    [self startClockWithTime:self.time];
}

- (void)startClockWithTime:(NSInteger)time{
    self.time = time;
    self.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.activityView stopAnimating];
    });
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(clockAction) userInfo:nil repeats:YES];
    self.showStopClockBtnText.length > 0 ? (self.showButtonText = self.showStopClockBtnText) : (self.showButtonText = @"重新发送");
}

- (void)clockAction{
    if(self.time <= 0){
        if(self.timer){
            [self.timer invalidate];
            self.timer = nil;
        }
        [self setTitle:self.showButtonText forState:UIControlStateNormal];
        [self setTitle:self.showButtonText forState:UIControlStateHighlighted];
        if (self.isRevise) {
            self.backgroundColor = self.showStopBackColor;
            [self setTitleColor:self.showStopTextColor forState:UIControlStateNormal];
        }else {
            self.backgroundColor = [UIColor colorWithRed:80/255.0f green:144/255.0f blue:254/255.0f alpha:1.0];
        }
        
        self.enabled = YES;
    }else{
        self.time--;
        NSString *timeStr;
        if (self.isRevise) {
            timeStr = [NSString stringWithFormat:@"%@%lds%@",self.showRuningClockFrontBtnText,self.time,self.showRuningClockBackBtnText];
        }else{
            timeStr = [NSString stringWithFormat:@"%@(%lds)",self.showButtonText,self.time];
        }
        
        [self setTitle:timeStr forState:UIControlStateNormal];
        [self setTitle:timeStr forState:UIControlStateHighlighted];
        if (self.isRevise) {
            self.backgroundColor = self.showRuningBackColor;
            [self setTitleColor:self.showRuningtextColor forState:UIControlStateNormal];
        }else{
            self.backgroundColor = [UIColor lightGrayColor];
        }
    }
}

- (void)stopClock{
    [self.activityView stopAnimating];
    if(self.timer){
        [self.timer invalidate];
        self.timer = nil;
    }
    [self setTitle:self.showButtonText forState:UIControlStateNormal];
    [self setTitle:self.showButtonText forState:UIControlStateHighlighted];
    self.enabled = YES;
}

- (void)stopActivityAnimation{
    [self.activityView stopAnimating];
    [self setTitle:self.showButtonText forState:UIControlStateNormal];
    [self setTitle:self.showButtonText forState:UIControlStateHighlighted];
}

- (void)smsButtonAction:(UIButton *)sender{
    [self.activityView startAnimating];
    if (self.isRevise) {
        
    }else{
        [self setTitle:@"" forState:UIControlStateNormal];
        [self setTitle:@"" forState:UIControlStateHighlighted];
    }
    if(self.smsButtonAction){
        self.smsButtonAction(self);
    }
}

- (void)clockWillResignAction{
    self.beginTime = [[NSDate date] timeIntervalSince1970];
}

- (void)clockBecomeActive{
    NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970];
    if(self.timer){//判断定时器是否有启动
        if(endTime - self.beginTime > 0){
            NSInteger totalTime = ceil(endTime - self.beginTime);
            self.time -= totalTime;
        }
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
